package controller

import (
	"fmt"
	"strconv"
	"web_app/dao/mysql"
	"web_app/logic"
	"web_app/models"
	"web_app/pkg/snowflake"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

//创建评论
func CommentHandler(c *gin.Context) {
	comment := new(models.Comment)
	if err := c.BindJSON(comment); err != nil {
		fmt.Println(err)
		ResponseError(c, CodeInvalidParam)
		return
	}
	//生成帖子id
	commentId, err := snowflake.GetID()
	if err != nil {
		zap.L().Error("snowflake.GetID() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	//获取发评论者id
	userId, err := GetCurrentUser(c)
	if err != nil {
		zap.L().Error("GetCurrentUser() failed", zap.Error(err))
		ResponseError(c, CodeNeedLogin)
		return
	}
	comment.CommentId = commentId
	comment.AuthorId = userId
	//创建帖子
	if err := mysql.CreateComment(comment); err != nil {
		zap.L().Error("mysql.CreatePost(&post) failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, nil)
}

//查询指定帖子的评论列表
func CommentListHandler(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		ResponseError(c, CodeInvalidParam)
		return
	}
	data, err := logic.GetCommentListById(id)
	//fmt.Println(data)
	if err != nil {
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}
